#include <iostream>

using namespace std;

int main() {
    int a;
    cin >> a;
    for (int i = 0; i < a-1; ++i) {
        int m, n, x, y;
        cin >> m >> n >> x >> y;
        for (int j = 0; j < 1000000; ++j) {
            if (j % m == n && j % x == y) {
                cout << j << endl;
                break;
            }
        }
    }
}